--[[
    @Author       : baidwwy
    @Date         : 2021-02-11 11:49:09
    @LastEditTime : 2021-03-09 04:04:56
--]]

local _ENV = require("GGE界面")
local lid = 0
local function compare(a,b) return a._lay < b._lay end
local function sort(self)
    lid = lid +1
    self._lay = lid
    -- if lid>0xFFFF then
    --     for k,v in pairs(self.父控件.子控件) do
    --         v._lay = v._lay-0xFFFF
    --     end
    -- end
    table.sort(self.父控件.子控件,compare)
end
GUI窗口 = class("GUI窗口",GUI控件)
GUI窗口._type = 7
function GUI窗口:初始化()
    
    self._lay = 0
    self.相对坐标 = false
end

function GUI窗口:置可见(v,s)
    GUI控件.置可见(self,v,s)
    if v and self.父控件 then
        sort(self)
    end
end

function GUI窗口:_消息事件(msg)
    if self.是否禁止 then
        return 
    end
    if self.父控件 then--如果按下，置顶，子控件会吃消息，所以放前面
        for _,v in ipairs(msg.鼠标) do
            if v.type==SDL.鼠标_按下 then
                if self:检查透明(v.x,v.y) then
                    sort(self)
                end
                break
            end
        end
    end
    GUI控件._消息事件(self,msg)

    for _,v in ipairs(msg.鼠标) do
        if v.type==SDL.鼠标_按下 then
            if self:检查透明(v.x,v.y) then
                if v.button==SDL.BUTTON_LEFT then
                    self._lx,self._ly = v.x-self.x,v.y-self.y
                    self._ldown = v.x..v.y
                    self:发送消息("左键按下",v.x,v.y,msg)
                elseif v.button==SDL.BUTTON_RIGHT then
                    self._rdown = v.x..v.y
                    self:发送消息("右键按下",v.x,v.y,msg)
                end
                v.x = -9999;v.y = -9999
            end
        elseif v.type==SDL.鼠标_弹起 then
            if self:检查透明(v.x,v.y) then
                if v.button==SDL.BUTTON_LEFT then
                    if self._ldown==v.x..v.y then
                        self:发送消息("左键弹起",v.x,v.y,msg)
                    end
                elseif v.button==SDL.BUTTON_RIGHT then
                    if self._rdown and self:发送消息("右键弹起",v.x,v.y,msg)~=false then
                        self:置可见(false)
                    end
                end
                v.x = -9999;v.y = -9999
            end
            self._lx    = nil
            self._ly    = nil
            self._ldown = nil
            self._rdown = nil
        elseif v.type==SDL.鼠标_移动 then
            if self._lx and v.state==SDL.BUTTON_LMASK then
                self.x,self.y = v.x-self._lx,v.y-self._ly
            end
            if self:检查透明(v.x,v.y) then
                self:发送消息("获得鼠标",v.x,v.y,msg)
                v.x = -9999;v.y = -9999
            end
        end
    end
    
    self:发送消息("消息事件",msg)
end
